package com.xiaoshuai.plat.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xiaoshuai.plat.common.weixin.WXConstants;
import com.xiaoshuai.plat.model.WXUserInfo;
import com.xiaoshuai.plat.service.WXUserInfoService;
import com.xiaoshuai.plat.util.weixin.WeixinUtil;
import com.xiaoshuai.plat.vo.AccessToken;
import com.xiaoshuai.plat.vo.OAuthInfo;

/**
 * oauth获取用户信息并保存到mongodb
 * @author 宗潇帅
 * @Title WXOauthController
 * @时间   2017-1-4上午11:06:14
 */
@Controller
@RequestMapping(value="/wx")
public class WXOauthController {
	
	
	private static Logger logger = Logger.getLogger(WXOauthController.class);
	@Autowired
	private WXUserInfoService wxUserInfoService;
	/**
	 * oauth获取用户相关信息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/oauth",method={RequestMethod.POST,RequestMethod.GET})
	public String oauth(HttpServletRequest request,HttpServletResponse response) throws Exception{
			//接受参数
			HttpSession httpSession = request.getSession();
			String code = request.getParameter("code");
			String scope = request.getParameter("scope");
			logger.info("==============[OAuthServlet]获取网页授权code="+code);
			logger.info("==============[OAuthServlet]获取网页跳转权限="+scope);
			if(null != code && !"".equals(code)){
				logger.info("==============[OAuthServlet]获取网页授权code不为空，code="+code);
				//根据code换取openId
				OAuthInfo oa = WeixinUtil.getOAuthOpenId(WXConstants.appId,WXConstants.appSecret,code);
				//第一次获取到存到session里面 防止用户刷新页面
				if(oa!=null){
					httpSession.setAttribute("openid", oa.getOpenId());
				}else{
					//如果用户是刷新页面。则读取session的openid 
					Object openid = httpSession.getAttribute("openid");
					if(openid!=null){
						OAuthInfo authInfo = new OAuthInfo();
						String openids = openid.toString();
						System.out.println("刷新页面留存的openid"+openids);
						authInfo.setOpenId(openids);
						oa = authInfo;
					}else{
						//session也为空 建议用户重新进入页面
//						request.getRequestDispatcher("/warn.jsp").forward(request, response);
						return "";
					}

				}
				AccessToken oasign = WXConstants.ACCESS_TOKEN;
				WXUserInfo info = WeixinUtil.getWXUserInfo(oasign.getToken(), oa.getOpenId());
				if(!"".equals(oa) && null != oa){
					logger.info("==============[OAuthServlet]获取网页授权openID="+oa.getOpenId());
					//保存信息
					try {
						wxUserInfoService.insert(info);
						request.setAttribute("openid", oa.getOpenId());
						request.setAttribute("nickname", info.getNickname());
						request.setAttribute("headimgurl", info.getHeadimgurl());
						request.setAttribute("city", info.getCity());
						request.getRequestDispatcher("/index.jsp").forward(request, response);
						return null;
					} catch (Exception e) {
						e.printStackTrace();
						logger.info("保存失败"+e.getMessage());
					}
				}else{
					logger.info("==============[OAuthServlet]获取网页授权openId失败！");
				}
			}else{
				logger.info("==============[OAuthServlet]获取网页授权code失败！");
			}
			return null;
	}
}
